//
//  CSSHomeTableViewController.swift
//  weibo28
//
//  Created by chushushan on 16/5/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

private let HomeTableViewCellIdentifier = "HomeTableViewCellIdentifier"


class CSSHomeTableViewController: CSSVisitorTableViewController {

//    //获取微博数据
//    var statusList: [CSSStatus]?
    
    
    private lazy var statusListViewModel: CSSStatusListViewModel = CSSStatusListViewModel()
    
    //上拉加载视图
    private lazy var pullUpView: UIActivityIndicatorView = {
        
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        view.color = UIColor.orangeColor()
        return view
   
    }()
    
    //系统下拉刷新
    private lazy var refreshCtr: UIRefreshControl = {
    
        let ctr = UIRefreshControl()
        return ctr
    }()
    
    //自定义的refreshCtr,自定义下拉刷新
    private lazy var pullDownView: CSSRefreshContol = {
    
        let ctr = CSSRefreshContol()
        return ctr
    }()
    
    //tip动画的控件
    private lazy var tipLabel: UILabel = {
    let label = UILabel(textColor: UIColor.whiteColor(), fontSize: 12)
        label.textAlignment = .Center
        label.backgroundColor = UIColor.orangeColor()
        label.text = "新数据"
        label.hidden = true
        return label
    
    }()
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if userLogin {
        
            setupUI()
            
            setupTableView()
//            requestStatus()
            //调用请求微博数据
            loadStatus()
            
        } else {
        //未登录的状态下
            visitorView?.setVistorInfo(nil, imageName: nil)
        }
    }
    
    //把tip视图添加到导航栏下面
    private func setupUI() {
    
        if let nav = self.navigationController {
        tipLabel.frame = CGRectMake(0, CGRectGetMaxY(nav.navigationBar.frame) - 35, tableView.frame.size.width, 35)
        nav.view.insertSubview(tipLabel, belowSubview: nav.navigationBar)
        }
    
    
    }
    
    
    //注册cell
    private func setupTableView() {
    
        tableView.registerClass(CSSStatusTableViewCell.self, forCellReuseIdentifier: HomeTableViewCellIdentifier)
        
       //自动获取行高
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 200
        
        //去掉cell的分割线
        tableView.separatorStyle = .None
        
        //设置上拉加载视图
        tableView.tableFooterView = pullUpView
        pullUpView.sizeToFit()
      
//        //下拉刷新的事件
//        refreshCtr.addTarget(self, action: "pullDownRefresh", forControlEvents: .ValueChanged)
    
        //系统下拉刷新
        //refreshCtr是继承自UIControl，可以处理响应
//        tableView.addSubview(refreshCtr)
        //系统第二种
//        self.refreshControl = refreshCtr
        
        //下拉刷新的事件
        pullDownView.addTarget(self, action: "pullDownRefresh", forControlEvents: .ValueChanged)
        
        //自定义的refreshCtr
        tableView.addSubview(pullDownView)
        
        
        
    }
    
    //下拉刷新事件
    @objc  private func pullDownRefresh() {
    
        
        
//        //停止动画
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
//            
//            self.refreshCtr.endRefreshing()
//        }
        //加载数据
        loadStatus()
    }
    
    private func startAnimation(message: String) {
    
        if tipLabel.hidden == false {
        
            return
        }
        
        tipLabel.text = message
        tipLabel.hidden = false
        
        UIView.animateWithDuration(1, animations: { () -> Void in
            self.tipLabel.transform = CGAffineTransformMakeTranslation(0, self.tipLabel.frame.size.height)
            }) { (_) -> Void in
                UIView.animateWithDuration(1, animations: { () -> Void in
                    self.tipLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        
                     self.tipLabel.hidden = true
                })
        }
    
    
    }
    
    

    
    //请求微博数据
    private func loadStatus() {
    
        //请求数据
        statusListViewModel.requestStatus(pullUpView.isAnimating(), complete: { (isSuccess, message) -> () in
            
            
            if !self.pullUpView.isAnimating() {
               self.startAnimation(message)
        
            }
            
            //关闭动画
            self.endRefreshing()
            
            if isSuccess {
                //刷新数据
                self.tableView.reloadData()
            }
           
            
        })
    
    }
    
    //关闭动画
    private func endRefreshing() {
    
        pullUpView.stopAnimating()
        
        refreshCtr.endRefreshing()
        
        pullDownView.endRefreshing()
    }
    
    


}


// MARK: - 数据源代理方法
extension CSSHomeTableViewController {
    
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListViewModel.statusList?.count ?? 0
    }
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeTableViewCellIdentifier, forIndexPath: indexPath) as! CSSStatusTableViewCell
//        cell.textLabel?.text = statusList![indexPath.row].user?.screen_name

        cell.statusViewModel = statusListViewModel.statusList![indexPath.row]
        
        //取消cell的选中样式
        cell.selectionStyle = .None
        
        return cell
        
    }
    
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
//        print("当前微博序号\(indexPath.row)")
        
        if indexPath.row == statusListViewModel.statusList!.count - 1 && !pullUpView.isAnimating() {
        
//        print("当前是最后一条微博")
            
            //开启动画
            pullUpView.startAnimating()
            //请求加载数据
            loadStatus()
            
        }
        
    }
    
    
}










